using System.Collections.ObjectModel;
using System.Runtime.ConstrainedExecution;
using UnityEngine;

namespace BuildingSystem.Scripts
{
    public class Building : MonoBehaviour 
    {
        private const float GIZMOS_CELL_SIZE = .99f;

        private Transform _model;
        private bool _isSquare;

        public Vector2Int Size => _size;
        [SerializeField] private Vector2Int _size = Vector2Int.one;
        public Rect Rect => new Rect(transform.position.x, transform.position.z, _size.x, _size.y);

        private void Awake() 
        {   
            _model = transform.GetChild(0);
            _isSquare = _size.x == _size.y;   
        }

        public void SetActive(bool value)
        {
            var go = gameObject;
            if (value != go.activeSelf)
                go.SetActive(value);
        }

        public void Rotate()
        {
            var tmpX = _size.x;
            _size.x = _size.y;
            _size.y = tmpX;

            _model.rotation *= Quaternion.Euler(0, 90, 0);
            if (!_isSquare)
            {
                var x = _model.transform.localPosition.x;
                var z = _model.transform.localPosition.z; 
                _model.transform.localPosition = z == 0 ? new Vector3(0, 0, x) : new Vector3(z, 0, 0);
            }
        }

        private void OnDrawGizmos()
        {
            Gizmos.color = Color.magenta;
            for (int x = 0; x < _size.x; x++)
                for (int y = 0; y < _size.y; y++)
                    Gizmos.DrawWireCube(transform.position + new Vector3(x, 0, y), new Vector3(GIZMOS_CELL_SIZE, 0, GIZMOS_CELL_SIZE));
        }
    }
}